package org.example.config;

import cn.hutool.core.io.watch.SimpleWatcher;
import cn.hutool.core.io.watch.WatchMonitor;
import cn.hutool.core.io.watch.watchers.DelayWatcher;
import cn.hutool.setting.Setting;
import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.nio.file.Path;
import java.nio.file.WatchEvent;

@Component
//@ConditionalOnProperty(prefix = "spring.datasource", name = "update-type",havingValue="file",matchIfMissing=false)
//public class UpdateDBSourceByFile implements CommandLineRunner {
public class UpdateDBSourceByFile {

    private static final Logger LOGGER = LoggerFactory.getLogger(UpdateDBSourceByFile.class);

    @Autowired()
    DataSource dataSource;

    public UpdateDBSourceByFile() {

    }

//    @Override
    @PostConstruct
    public void run() throws Exception {
        LOGGER.info("UpdateDBSourceByFile init");
        try {
            SimpleWatcher watcher = new SimpleWatcher() {
                @Override
                public void onModify(WatchEvent<?> event, Path currentPath) {
                    Setting settings = new Setting("D:\\gitee\\test\\springboot\\mybatisplus\\sbmybatisplus\\src\\main\\resources\\db.ini");
                    settings.load();
                    String type = settings.getByGroup("type", "");
                    String url = settings.getByGroup("url", "");
                    String driver = settings.getByGroup("driver", "");
                    String username = settings.getByGroup("username", "");
                    String password = settings.getByGroup("password", "");
                    ((DruidDataSource) dataSource).setUrl(url);
                    ((DruidDataSource) dataSource).setUsername(username);
                    ((DruidDataSource) dataSource).setPassword(password);
                    ((DruidDataSource) dataSource).setDriverClassName(driver);
                    System.out.println("type=" + type);
                    LOGGER.info("文件修改了：" + currentPath.toString());
                }
            };
            WatchMonitor monitor = WatchMonitor.createAll("D:\\gitee\\test\\springboot\\mybatisplus\\sbmybatisplus\\src\\main\\resources\\db.ini", new DelayWatcher(watcher, 500));
            monitor.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
